package com.jin.webvideo.config.filter.access.rule;

import com.jin.webvideo.base.util.CollectionsUtil;
import com.jin.webvideo.config.filter.access.GlobalStore;
import com.jin.webvideo.config.filter.access.handler.AccessHandler;
import com.jin.webvideo.entity.SessionStore;
import com.jin.webvideo.entity.User;
import com.jin.webvideo.util.base.StringUtil;
import lombok.Data;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Data
public class RoleAccessRule implements AccessHandler.AccessRule {
    private List<String> roleTemplate;
    public RoleAccessRule() {

    }
    public RoleAccessRule(String... roleTemplate) {
        this.roleTemplate = Arrays.asList(roleTemplate);
    }

    private boolean chkRole(List<User.Role> roles) {
        for (String template : roleTemplate) {
            for (User.Role r : roles) {
                if (StringUtil.match(template, r.getName())) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean compute(GlobalStore globalStore, SessionStore store, HttpServletRequest request) {
        List<User.Role> roles = Collections.singletonList(User.Role.ROLE_UNSAFE);
        if (store != null) {
            roles = store.roles();
        }
        return chkRole(roles);
    }
}
